package com.fone.player.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.client.Reporter;
import com.fone.player.constant.FoneConstant;
import com.fone.player.sns.ISNSShareManager.ShareStateListener;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.bean.ShareInfo;
import com.fone.player.sns.impl.SNSShareManager;
import com.fone.player.sns.util.SNSUtil;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.SerializationUtil;

public class ShareEditActivity extends BaseActivity implements OnClickListener {

	private static String TAG = "ShareEditActivity";
	
	private Button backBt,sendBt;
	private TextView sharePlatformTitle;
	private EditText editContent;
	private Intent intent;
	private ShareInfo mShareInfo;
	private SNSShareManager mShareManager;
	private LinearLayout waitting;
	
	private Handler mHandler;
	
	private static final int SNS_SHARE_SUCCESS = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_edit_view);
		if(!getShareInfo()){
			L.v(TAG, "onCreate","shareInfo is null !!");
			finish();
		}
		initView();
		iniHandler();
		iniShareManager();
		editContent.requestFocus();
		editContent.addTextChangedListener(new TextWatcher() {
			private String temp="";
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				temp = s.toString();
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				if(temp.length()>120){
					FoneUtil.showToast(mContext, "已经达到最大字数");
					editContent.setText(temp.substring(0,120));
					editContent.setSelection(120);//设置光标在最后
				}
			}
		});
		showInput(editContent); 
	}
	
	private void initView(){
		waitting = (LinearLayout) findViewById(R.id.share_edit_waitting_ll);
		backBt = (Button) findViewById(R.id.common_title_left_bt);
		sendBt = (Button) findViewById(R.id.common_title_right_bt);
		sharePlatformTitle = (TextView) findViewById(R.id.common_left_title_tv);
		editContent = (EditText) findViewById(R.id.share_content_et);
		
		editContent.addTextChangedListener(new TextWatcher() {
			private String temp="";
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				temp = s.toString();
			}
			@Override
			public void afterTextChanged(Editable s) {
				if(temp.length()>120){
					FoneUtil.showToast(mContext, "已经达到最大字数");
					editContent.setText(temp.substring(0,120));
					editContent.setSelection(120);//设置光标在最后
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
		});
		
		if(!TextUtils.isEmpty(mShareInfo.text)){
			editContent.setText(mShareInfo.text);
		}
		backBt.setOnClickListener(this);
		sendBt.setOnClickListener(this);
		
		setTitle(mShareInfo);
		sharePlatformTitle.setVisibility(View.VISIBLE);
		sendBt.setText("发送");
	}
	
	@SuppressLint("HandlerLeak")
	private void iniHandler(){
		mHandler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SNS_SHARE_SUCCESS:
						waitting.setVisibility(View.GONE);
						finish();
					break;
				default:
					break;
				}
			}
			
		};
	}
	
	private boolean getShareInfo(){
		intent = getIntent();
		Bundle bundle = intent.getExtras();
		mShareInfo = (ShareInfo) bundle.get("shareInfo");
		return mShareInfo!=null;
	}
	
	private void setTitle(ShareInfo info){
		String title = "";
		if(info.SNSType!=0&&sharePlatformTitle!=null){
			switch (info.SNSType) {
			case SNSShareManager.SINA_WEIBO_TYPE:
				title="新浪微博分享";
				break;
			case SNSShareManager.TENCENT_WEIBO_TYPE:
				title="腾讯微博分享";
				break;
			case SNSShareManager.TENCENT_QQ_TYPE:
				title="QQ空间分享";
				break;
			default:
				break;
			}
		}
		sharePlatformTitle.setText(title);
	}
	
	private void iniShareManager(){
		mShareManager = SNSShareManager.getInstance();
		mShareManager.setShareStateListener(new ShareStateListener() {
			
			@Override
			public void shareAction(int action, String info) {
				//提示成功 失败 
				switch (action) {
				case ShareStateListener.SHARING :
					waitting.setVisibility(View.VISIBLE);
					L.v(TAG, "iniShareManager", " shareAction : SHARING");
					break;
				case ShareStateListener.SHARE_SUCCESS :
					L.v(TAG, "shareAction", "countID : " + mShareInfo.countID + " comeFrom : " + mShareInfo.comeFrom);
					if(mShareInfo.comeFrom!=0){
						//TODO  分享成功上报
						Reporter.logShare(String.valueOf(mShareInfo.countID), 1, mShareInfo.comeFrom);
					}
					Toast.makeText(ApplicationManage.getGlobalContext(), "分享成功", Toast.LENGTH_SHORT).show();
					mHandler.sendEmptyMessage(SNS_SHARE_SUCCESS);
					L.v(TAG, "iniShareManager", " shareAction : SHARE_SUCCESS");
					break;
				case ShareStateListener.SHARE_FAILED :
					Toast.makeText(ApplicationManage.getGlobalContext(), info, Toast.LENGTH_SHORT).show();
					waitting.setVisibility(View.GONE);
					L.v(TAG, "iniShareManager", " shareAction : SHARE_FAILED");
					finish();
					break;
				case ShareStateListener.SHARE_CANCEL :
					waitting.setVisibility(View.GONE);
					L.v(TAG, "iniShareManager", " shareAction : SHARE_CANCEL");
					finish();
					break;
				default:
					break;
				}
				
			}
			
			@Override
			public void onUserInfoComplete(SNSUserInfo user) {
				//更新本地的授权信息
				if(user.snsType==SNSShareManager.SINA_WEIBO_TYPE){
					if(mShareManager.sinaLocalInfo==null
							||mShareManager.sinaLocalInfo.accessToken!=user.accessToken
								||mShareManager.sinaLocalInfo.expiresTime!=user.expiresTime){
						mShareManager.sinaLocalInfo=user;
						SerializationUtil.wirteSNSInfoSerialization(getApplicationContext(), user, SNSShareManager.SINA_WEIBO_LOCALSNSINFO);
					}
				}else if(user.snsType==SNSShareManager.TENCENT_WEIBO_TYPE){
					if(mShareManager.tencentLocalInfo==null
							||mShareManager.tencentLocalInfo.accessToken!=user.accessToken
								||mShareManager.tencentLocalInfo.expiresTime!=user.expiresTime){
						mShareManager.tencentLocalInfo=user;
						SerializationUtil.wirteSNSInfoSerialization(getApplicationContext(), user, SNSShareManager.TENCENT_WEIBO_LOCALSNSINFO);
					}
				}
			}
		});
	}
	
	private void showInput(View view){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN); 
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); 
	}
	
	private void hideInput(){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
	}
	
	private boolean checkShareContent(ShareInfo shareInfo){
		String content = editContent.getText().toString().trim();
		if(!TextUtils.isEmpty(content)){
			if((shareInfo.SNSType == SNSShareManager.TENCENT_WEIBO_TYPE
					||shareInfo.SNSType == SNSShareManager.SINA_WEIBO_TYPE)
						&&TextUtils.isEmpty(shareInfo.titleUrl)){
				//TODO 拼接后缀
				shareInfo.text = content + " " + shareInfo.titleUrl;
			}else{
				//TODO 拼接后缀
				shareInfo.text = content;
			}
			return true;
		}
		FoneUtil.showToast(mContext, "分享内容不能为空");
		return false;
	}
	
	/**
	 * 获取服务端配置的分享语
	 * @return
	 */
	private String getShareWord(){
		String shareWord = FoneUtil.getDeclaration(mContext, FoneConstant.SHARE_WORD);
		if(TextUtils.isEmpty(shareWord.trim())){
			shareWord = "分享自@100tv";
		}
		return shareWord;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(waitting.getVisibility()==View.VISIBLE){
			waitting.setVisibility(View.VISIBLE);
			SNSUtil.stopSNS();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.common_title_left_bt:
			hideInput();
			finish();
			break;
		case R.id.common_title_right_bt:
			if(!checkShareContent(mShareInfo)||!FoneUtil.isNetOkWithToast(mContext)){
				return;
			}
			hideInput();
			waitting.setVisibility(View.VISIBLE);
			
			if(mShareInfo.SNSType != SNSShareManager.TENCENT_QQ_TYPE){//如果不是QQ空间分享
				//拼接后缀
				mShareInfo.text = mShareInfo.text
						+" "+ mShareInfo.videoUrl
						+" ，" + this.getResources().getString(R.string.select_share_word_suffix)
						+ " " + getShareWord();
				L.v(TAG, "onClick","text : " + mShareInfo.text);
			}
			mShareManager.shareMessage(mShareInfo);
			break;

		default:
			break;
		}
	}
	
}
